﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

/*
 * Author:Conis
 * Date:
 * Description:SQL条件
 */

namespace Conis.Squirrel.SqlBuilder
{
    public abstract class BaseCondition : BaseConditionBlock
    {
        /// <summary>
        /// 实现SQL条条件的类
        /// </summary>
        public BaseCondition()
            : base(Connector.And)
        {
            this.container = new StringBuilder();
            this.paramsList = new List<IDataParameter>();
        }
        /// <summary>
        /// 返回参数列表
        /// </summary>
        /// <returns></returns>
        public IDataParameter[] Parameters()
        {
            return this.paramsList.ToArray();
        }

        /// <summary>
        /// 返回SQL条件语句的字符串
        /// </summary>
        /// <param name="prefix">是否包含前缀</param>
        /// <param name="doCreate">是否执行创建动作</param>
        /// <returns></returns>
        public string ToString(bool prefix, bool doCreate)
        {
            //执行创建操作
            if (doCreate)
            {
                this.Create();
            }
            string result = this.container.ToString();
            //需要前缀，且SQL条件语句不为空
            if (prefix && result != string.Empty)
            {
                //需要增加Where，以及剔除最新面的And
                result = " WHERE " + result.Substring(4);
            }
            return result;
        }

        /// <summary>
        /// 返回SQL语句条件语句的字符串
        /// </summary>
        /// <param name="prefix">是否包含前缀</param>
        /// <returns></returns>
        public string ToString(bool prefix)
        {
            return this.ToString(prefix, false);
        }

        /// <summary>
        /// 创建SQL条件语句
        /// </summary>
        public new void Create()
        {
            base.Create();
        }

        /// <summary>
        /// 循环前的操作
        /// </summary>
        protected override void LoopBefore()
        {
            if (this.currentIndex == 0)
            {
                this.list[0].Connector = Connector.And;
            }
            this.container.Append(this.Connector.ToSql());
            //不需要加上括号，覆盖掉ConditionBlock的方法
        }

        /// <summary>
        /// 必需覆盖父级的方法，因为Condition类不需要右括号
        /// </summary>
        protected override void LoopAfter()
        {
            //
        }
    }
}
